<template>
  <MdEditor
    v-model="contentRef"
    :placeholder="placeholder"
    default-mode="split"
    :preview-options="{ markdown: { breaks: true } }"
    :onUploadImg="onUploadImg"
    :previewTheme="theme"
  />
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from "vue";
import { MdEditor } from "md-editor-v3";
import { uploadFile } from "@/apis/upload";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "在这里输入 Markdown 内容...",
  },
  theme: {
    type: String,
    default: "vuepress", // 预览主题，默认使用
  },
});

const emit = defineEmits(["update:modelValue"]);
const contentRef = ref(props.modelValue);

// 同步本地内容到父组件
watch(contentRef, (newValue) => {
  emit("update:modelValue", newValue);
});

// 同步父组件内容到本地
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue !== contentRef.value) {
      contentRef.value = newValue;
    }
  },
  { immediate: true }
);

// 图片上传处理
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((resolve, reject) => {
        const form = new FormData();
        form.append('file', file);
        // 上传图片
        uploadFile(form).then((res) => resolve(res)).catch((error) => reject(error));
      });
    })
  );

  callback(res.map((item) => item.data.url));
};
</script>
